package com.easy.carpanel.ui;

import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.easy.carpanel.R;
import com.easy.carpanel.uart.uartJni;
import com.easy.carpanel.until.CarUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.IOException;
import java.util.List;

public class Car2Activity extends AppCompatActivity {
    int bpvalue = 79;  //bp值
    int hrvaule = 65;// hr值
    int tvaule = 36; //t值
    int pressurevaule = 980; //压强参数

    @BindView(R.id.bptextview)
    TextView bptextview;     //bp 参数
    @BindView(R.id.hrtextview)
    TextView hrtextview;      //hr 参数
    @BindView(R.id.ttextview)
    TextView ttextview;       //t 参数
    @BindView(R.id.temperaturetextview)
    TextView temperaturetextview;  //温度
    @BindView(R.id.pressuretextview)
    TextView pressuretextview;    //压强
    @BindView(R.id.healthImageView)
    ImageView healthImageView;      //hr 参数


    @BindView(R.id.img_weather)
    ImageView imgWeather;      //天气图片
    private boolean isFristWeather = true;
    private String addresscode;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    private Runnable readerRunnable;
    private Runnable weatherRunnable;
    byte[] read_buf = new byte[1024];
    Handler handler = new Handler();
    int fd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car2);
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        bptextview.setText(bpvalue + "");
        hrtextview.setText(hrvaule + "");
        ttextview.setText(tvaule + "");
        pressuretextview.setText(pressurevaule + "hpa");


        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
                    //给定位客户端对象设置定位参数
                    mLocationClient.setLocationOption(mLocationOption);
                    //启动定位
                    mLocationClient.startLocation();

                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(Car2Activity.this, "GPS定位权限没有打开，请打开！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    @OnClick(R.id.hrtextview)
    public void onViewClicked() {
//        Intent intent = new Intent(Car2Activity.this, BmpActivity.class);
//        startActivity(intent);
    }


    @Override
    protected void onResume() {
        String device = "/dev/ttyS4";
        fd = uartJni.open(device, 115200);
        Log.d("jiangyunwei", "open the device of " + device + ", fd is: " + fd);

        readerRunnable = new Runnable() {
            @Override
            public void run() {
                int read_count = uartJni.read(fd, read_buf, read_buf.length);

                if (read_count < 0) {
                    read_count = 0;
                }
                String  value =  CarUtil.toHex(read_buf, read_count);
                Log.d("jiangyunwei",value);
                System.out.println(value);
                List<String> list = CarUtil.getStrList(value,2);
                if(list==null || list.size()<=8){
                    handler.postDelayed(this, 500);
                    return;
                }
                if(list.size()>=28){
                    int  tag = (int) Long.parseLong(list.get(27),16);
                    if(tag == 0){
                        Car2Activity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Intent    intent  =  new Intent(Car2Activity.this,BmpActivity.class);
//                                Car2Activity.this.startActivity(intent);
                            }
                        });
                    }
                }
                bpvalue =  (int) Long.parseLong(list.get(22),  16);
                hrvaule =  (int) Long.parseLong(list.get(24),  16);
                int tvaule1 =  (int) Long.parseLong(list.get(25),  16);
                int tvaule2 =  (int) Long.parseLong(list.get(26),  16);
                tvaule = tvaule1+ tvaule2*10/256 ;
                pressurevaule =  (int) Long.parseLong(list.get(4),  16);
                bptextview.setText(bpvalue+"");
                if (!(hrvaule + "").equals(hrtextview.getText())) {
                    healthImageView.setImageResource(R.drawable.heath_animation);
                    AnimationDrawable animationDrawable = (AnimationDrawable) healthImageView.getDrawable();
                    animationDrawable.start();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Car2Activity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    animationDrawable.stop();
                                    healthImageView.setImageResource(R.mipmap.healthbd);
                                }
                            });
                        }
                    }, 5000);
                }

                hrtextview.setText(hrvaule+"");
                ttextview.setText(tvaule+"");
                pressuretextview.setText(pressurevaule+"hpa");

                handler.postDelayed(this, 500);
                //相当于定时器，每隔1s执行一次该线程
            }
        };
        handler.post(readerRunnable);

        super.onResume();
    }

    @Override
    protected void onPause() {
        uartJni.close(fd);
        handler.removeCallbacks(readerRunnable);
        handler.removeCallbacks(weatherRunnable);
        super.onPause();
    }


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

            if (isFristWeather) {
                isFristWeather = false;
                addresscode = aMapLocation.getAdCode();
                initweather(addresscode);
            }


        }
    };


    private void initweather(String addresscode) {

        OkHttpClient client = new OkHttpClient();
        String url = "https://restapi.amap.com/v3/weather/weatherInfo?" + "key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
        Request request = new Request.Builder().get()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //一般会得到Json数据，这时候就要用Json解析的一系列方法处理了，网上都可查这里不多讲
                String jsonString = response.body().string();
                //把访问url得到的数据打印出来
                JSONObject json = JSONObject.parseObject(jsonString);
                JSONArray livejson = json.getJSONArray("lives");
                if (livejson == null) {
                    return;
                }
                String weather = livejson.getJSONObject(0).getString("weather");
                String temperature = livejson.getJSONObject(0).getString("temperature");
                Car2Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        temperaturetextview.setText(temperature + "℃");
                    }
                });
                if (weather.contains("晴")) {
                    Car2Activity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgWeather.setImageResource(R.mipmap.qing);
                        }
                    });
                }
                if (weather.contains("多云")) {
                    Car2Activity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgWeather.setImageResource(R.mipmap.duoyun);
                        }
                    });

                }
                if (weather.contains("阴")) {
                    Car2Activity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgWeather.setImageResource(R.mipmap.yin);
                        }
                    });

                }
                if (weather.equals("雨夹雪")) {
                    Car2Activity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgWeather.setImageResource(R.mipmap.yujiaxue);
                        }
                    });
                } else if (weather.contains("雷")) {
                    Car2Activity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgWeather.setImageResource(R.mipmap.leiyu);
                        }
                    });
                } else if (weather.contains("雪")) {
                    Car2Activity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgWeather.setImageResource(R.mipmap.daxue);
                        }
                    });
                }
            }
        });
    }


}
